import axios from "axios";
import { Message, Loading } from "element-ui";
import store from "./../store";

/**
 * 全局的loading
 * 
 * 在每次接口请求前，打开loading
 * 接口请求结束关闭loading
 * 
 * 如果接口错误的话，那么loading是否关闭可以和产品讨论一下
 */

let loading = null

axios.interceptors.response.use((response) => {
  loading.close()
  if (response.data.code !== 1000) {
    Message.error(response.data.msg);
    throw new Error(response.data.msg);
  }
  return response.data;
}, (err) => {
  /**
   * 如果整个接口都报错了 如 404  500 400 401 403 302
   */
   loading.close()
});

axios.interceptors.request.use((config) => {
  loading = Loading.service({ fullscreen: true })
  config.headers["Authorization"] = `Bearer ${store.state.token}`;
  return config;
});

export default axios;
